home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 98 / Skunkware 98.iso / osr5 / sco / scripts / aw < prev    next >
Encoding:
AWK Script  |  1997-08-26  |  33.5 KB  |  921 lines

  1. #!/usr/local/bin/gawk -f
  2. # @(#) aw.gawk 2.1 97/02/24
  3. # 91/01/29 john h. dubois iii (john@armory.com)
  4. # 92/02/16 added help
  5. # 92/05/01 changed to #!awk script
  6. # 95/04/24 filbo@armory.com Pass arguments to w
  7. # 95/12/23 Work w/varying pos of Idle field.  Work around gawk+protlib bugs.
  8. # 95/12/26 Remove leading 'tty' from tty names.
  9. # 95/12/27 Remove meridian and one char from idle field.  This reduces lines
  10. #          to a length that will never wrap.  Added all options.
  11. # 96/01/20 Look for rcfile in $UHOME also.
  12. # 96/10/19 Added w option.  Deal with - in idle column.  Added x option.
  13.  
  14. BEGIN {
  15.     Name = "aw"
  16.     rcFile = "." Name
  17.     Usage = Name \
  18. " [-chx] [-i<time>] [-n<namelist>] [-u<utmpfile>] [-U<utmpxfile>] [-w<w>]\n"\
  19. "   [user ...]"
  20.     ARGC = Opts(Name,Usage,"i:Xlcw:d>hn:s:u:U:",0,"~/" rcFile ":$UHOME/" rcFile,
  21.     "IDLE,SHOWHOSTS,LSHOWHOSTS,NOCPU,W")
  22.     Min = 10
  23.     w = "/usr/bin/w"
  24.     if ("h" in Options) {
  25.     printf \
  26. "%s: do a 'w', but skip lines for users idle longer than a given time.\n"\
  27. "The output of 'w' is also reformatted to prevent lines from wrapping.\n"\
  28. "%s\n"\
  29. "Options:\n"\
  30. "Some of these options may be set in a configuration file named %s, which\n"\
  31. "is searched for in the invoking user's home directory and in the directory\n"\
  32. "specified by the environment variable UHOME, if it is set.  Variables are\n"\
  33. "assigned to with the syntax:  varname=value  or in the case of flags, by\n"\
  34. "simply putting the indicated variable name in the file without a value.\n"\
  35. "A variable assigned to in one of these files will override values assigned\n"\
  36. "to the same variable in one of the files read after it.  To turn off a\n"\
  37. "flag option and prevent it from being set in a file read later, assign it\n"\
  38. "a value of 0.  e.g. if SHOWHOSTS is set in $UHOME/%s, SHOWHOME=0\n"\
  39. "in $HOME/%s file will override it.  Flag options can be turned off on the\n"\
  40. "command line by following them immediately with \"-\", e.g. -c- to turn\n"\
  41. "off the c option in such a way that it cannot be turned on in a config\n"\
  42. "file.  Variable names appear in parentheses in the option descriptions.\n"\
  43. "-c: Do not show the JCPU and PCPU columns.  (NOCPU)\n"\
  44. "-h: Print this help.\n"\
  45. "-X: Print the names of hosts that users are remotely logged in from.\n"\
  46. "    (SHOWHOSTS)\n"\
  47. "-l: Print the full names of hosts that users are remotely logged in from.\n"\
  48. "    Only works with new 'w'.  (LSHOWHOSTS)\n"\
  49. "-i<time>: Specify the amount of time a user has to be idle to not be\n"\
  50. "    reported on, in the form [hours:]minutes.  The default is %d.  (IDLE)\n"\
  51. "-w<w>: Use <w> as the program to process the output of, instead of the\n"\
  52. "    default of %s (W)\n"\
  53. "-n<namelist>: Specify a kernel namelist other than the default of /unix.\n"\
  54. "-u<utmpfile>: Specify a utmp file other than the default of /etc/utmp.\n"\
  55. "-U<utmpxfile>: Specify a utmp extension file other than /etc/utmpx.\n",
  56.     Name,Usage,rcFile,rcFile,rcFile,Min,w
  57. # Looks like this isn't actually implemented despite what man page says.
  58. #"-s<swapdev>: Specify a swap device other than the default of /dev/swap."
  59.     exit(0)
  60.     }
  61.  
  62.     if ("d" in Options)
  63.     debug = Options["d"]
  64.     if ("w" in Options)
  65.     w = Options["w"]
  66.     if ("i" in Options) {
  67.     if ((Min = ms2sec(Options["i"])) == -1) {
  68.         print Name \
  69. ": Bad value given with -i: should be a time in the format [hours:]minutes" \
  70.         > "/dev/stderr"
  71.         exit 1
  72.     }
  73.     if (Min > 6039) {
  74.         print Name ": cannot take a value larger than 99:99 with -i." \
  75.         > "/dev/stderr"
  76.         exit 1
  77.     }
  78.     }
  79.     if (debug)
  80.     print "idle min: " Min
  81.     MakeSet(WOpts,"n:u:U:s",":")
  82.     Cmd = "exec " w
  83.     # Ugh
  84.     if (newW = ("l" in Options))
  85.     Cmd = Cmd " -X"
  86.     else if ("X" in Options)
  87.     Cmd = Cmd " -x"
  88.     for (Option in WOpts)
  89.     if (Option in Options)
  90.         Cmd = Cmd " -" Option " " Options[Option]
  91.     for (i = 1; i < ARGC; i++)
  92.     Cmd = Cmd " " ARGV[i]
  93.     # Must redir input from /dev/null due to interaction of gawk & protlib bugs
  94.     Cmd = Cmd " < /dev/null"
  95.     if (debug)
  96.     print "w command: " Cmd > "/dev/stderr"
  97.     Cmd | getline
  98.     print $0
  99.     Cmd | getline
  100.     if (newW)
  101.     doNewW()
  102.     else
  103.     doOldW()
  104. }
  105.  
  106. function meridTimeTo24(time,  Elem) {
  107.     split(time,Elem,":")
  108.     hour = Elem[1]
  109.     if (Elem[2] ~ "[pPmM]") {
  110.     hour += 12
  111.     if (hour == 24)
  112.         hour = 0
  113.     }
  114.     return sprintf("%d:%02d",hour,Elem[2])
  115. }
  116.  
  117. # Unfinished
  118. function doNewW(  user,tty,login,host,idle,format) {
  119.     format = "%-8s %-4s %5s %4s %-21s %s\n"
  120.     printf format,"User","TTY","Login","Idle","Hostname","What"
  121.     while ((Cmd | getline) == 1) {
  122.     idle = $4
  123.     if (idle == "-") {
  124.         idleF = ""
  125.         idle = 0
  126.     }
  127.     else
  128.         idle = idleF = ms2sec(idle)
  129.     if (debug)
  130.         print "idle time: " idle
  131.     if (idle < Min) {
  132.         user = $1
  133.         tty = substr($2,4)
  134.         login = meridTimeTo24($3)
  135.         host = $7
  136.         $1 = $2 = $3 = $4 = $5 = $6 = $7 = ""
  137.         sub("^ +","",$0)
  138.         printf format,user,tty,login,idleF,host,$0
  139.     }
  140.     }
  141. }
  142.  
  143. function doOldW() {
  144.     iStart = index($0,"Idle")-1
  145.     tStart = index($0,"Tty")
  146.     mStart = index($0,"n@")        # meridian info
  147.     hStart = mStart - 5        # hours
  148.     if (noCPU = "c" in Options) {
  149.     cStart = iStart+6
  150.     cLen = index($0,"PCPU") - cStart + 5
  151.     $0 = DelStr($0,cStart,cLen)
  152.     }
  153.     $0 = DelStr($0,mStart+2,1)
  154.     $0 = DelStr($0,mStart-6,2)
  155.     print DelStr($0,tStart+3,3)
  156.  
  157.     while ((Cmd | getline) == 1) {
  158.     idle = substr($0,iStart,5)
  159.     if (idle ~ "-") {    # replace - with space
  160.         $0 = PasteStr($0,iStart,"     ")
  161.         idle = 0
  162.     }
  163.     else
  164.         idle = ms2sec(idle)
  165.     if (idle < Min) {
  166.         # Do modifications from right to left,
  167.         # so that the column positions calculated will be correct
  168.         if (noCPU)
  169.         $0 = DelStr($0,cStart,cLen)
  170.         # if meridian is pm, add 12 to hour
  171.         if (substr($0,mStart,2) == "pm")
  172.         $0 = PasteStr($0,hStart,substr($0,hStart,2) + 12)
  173.         # discard meridian, and a char after it.  We can get away with
  174.         # removing a char between login time & idle because this program
  175.         # will not print lines with large idle times.
  176.         $0 = DelStr($0,mStart,3)
  177.         if (substr($0,tStart,3) == "tty")
  178.         $0 = DelStr($0,tStart,3)
  179.         print $0
  180.     }
  181.     if (debug)
  182.         print "idle time: " idle
  183.     }
  184. }
  185.  
  186. ### Begin Strings routines
  187.  
  188. # Delete the string starting at Start and having length Num from the middle
  189. # of string S, and return the remaining part.
  190. function DelStr(S,Start,Num) {
  191.     return substr(S,1,Start - 1) substr(S,Start+Num)
  192. }
  193.  
  194. # Paste NewStr into S at position Pos
  195. function PasteStr(S,Pos,NewStr,  e) {
  196.     e = length(S)+1    # The position after the end of S
  197.     if (e >= Pos)
  198.     return substr(S,1,Pos-1) NewStr substr(S,Pos+length(NewStr))
  199.     for (; e < Pos; e++)
  200.     S = S " "
  201.     return S NewStr
  202. }
  203.  
  204. # MakeSet: make a set from a list.
  205. # An index with the name of each element of the list
  206. # is created in the given array.
  207. # Input variables: 
  208. # Elements is a string containing the list of elements.
  209. # Sep is the character that separates the elements of the list.
  210. # Output variables:
  211. # Set is the array.
  212. # Return value: the number of elements added to the set.
  213. function MakeSet(Set,Elements,Sep,  i,Num,Names) {
  214.     Num = split(Elements,Names,Sep)
  215.     for (i = 1; i <= Num; i++)
  216.     Set[Names[i]]
  217.     return Num
  218. }
  219.  
  220. # Convert a time in the format [hours:]minutes to minutes, or alternately
  221. # convert a time in the format [minutes:]seconds to seconds.
  222. # The minutes/seconds are returned.
  223. # -1 is returned on error.
  224. function ms2sec(Time,  E,i) {
  225.     n = split(Time,E,":")
  226.     if (n != 1 && n != 2)
  227.     return -1
  228.     for (i in E)
  229.     if (E[i] !~ /^ *[0-9]+$/)
  230.         return -1
  231.     if (n == 1)
  232.     return E[1]
  233.     else
  234.     return E[1]*60 + E[2]
  235. }
  236.  
  237. ### Start of ProcArgs library
  238. # @(#) ProcArgs 1.11 96/12/08
  239. # 92/02/29 john h. dubois iii (john@armory.com)
  240. # 93/07/18 Added "#" arg type
  241. # 93/09/26 Do not count -h against MinArgs
  242. # 94/01/01 Stop scanning at first non-option arg.  Added ">" option type.
  243. #          Removed meaning of "+" or "-" by itself.
  244. # 94/03/08 Added & option and *()< option types.
  245. # 94/04/02 Added NoRCopt to Opts()
  246. # 94/06/11 Mark numeric variables as such.
  247. # 94/07/08 Opts(): Do not require any args if h option is given.
  248. # 95/01/22 Record options given more than once.  Record option num in argv.
  249. # 95/06/08 Added ExclusiveOptions().
  250. # 96/01/20 Let rcfiles be a colon-separated list of filenames.
  251. #          Expand $VARNAME at the start of its filenames.
  252. #          Let varname=0 and -option- turn off an option.
  253. # 96/05/05 Changed meaning of 7th arg to Opts; now can specify exactly how many
  254. #          of the vars should be searched for in the environment.
  255. #          Check for duplicate rcfiles.
  256. # 96/05/13 Return more specific error values.  Note: ProcArgs() and InitOpts()
  257. #          now return various negatives values on error, not just -1, and
  258. #          Opts() may set Err to various positive values, not just 1.
  259. #          Added AllowUnrecOpt.
  260. # 96/05/23 Check type given for & option
  261. # 96/06/15 Re-port to awk
  262. # 96/10/01 Moved file-reading code into ReadConfFile(), so that it can be
  263. #          used by other functions.
  264. # 96/10/15 Added OptChars
  265. # 96/11/01 Added exOpts arg to Opts()
  266. # 96/11/16 Added ; type
  267. # 96/12/08 Added Opt2Set() & Opt2Sets()
  268. # 96/12/27 Added CmdLineOpt()
  269.  
  270. # optlist is a string which contains all of the possible command line options.
  271. # A character followed by certain characters indicates that the option takes
  272. # an argument, with type as follows:
  273. # :    String argument
  274. # ;    Non-empty string argument
  275. # *    Floating point argument
  276. # (    Non-negative floating point argument
  277. # )    Positive floating point argument
  278. # #    Integer argument
  279. # <    Non-negative integer argument
  280. # >    Positive integer argument
  281. # The only difference the type of argument makes is in the runtime argument
  282. # error checking that is done.
  283.  
  284. # The & option is a special case used to get numeric options without the
  285. # user having to give an option character.  It is shorthand for [-+.0-9].
  286. # If & is included in optlist and an option string that begins with one of
  287. # these characters is seen, the value given to "&" will include the first
  288. # char of the option.  & must be followed by a type character other than ":"
  289. # or ";".
  290. # Note that if e.g. &> is given, an option of -.5 will produce an error.
  291.  
  292. # Strings in argv[] which begin with "-" or "+" are taken to be
  293. # strings of options, except that a string which consists solely of "-"
  294. # or "+" is taken to be a non-option string; like other non-option strings,
  295. # it stops the scanning of argv and is left in argv[].
  296. # An argument of "--" or "++" also stops the scanning of argv[] but is removed.
  297. # If an option takes an argument, the argument may either immediately
  298. # follow it or be given separately.
  299. # "-" and "+" options are treated the same.  "+" is allowed because most awks
  300. # take any -options to be arguments to themselves.  gawk 2.15 was enhanced to
  301. # stop scanning when it encounters an unrecognized option, though until 2.15.5
  302. # this feature had a flaw that caused problems in some cases.  See the OptChars
  303. # parameter to explicitly set the option-specifier characters.
  304.  
  305. # If an option that does not take an argument is given,
  306. # an index with its name is created in Options and its value is set to the
  307. # number of times it occurs in argv[].
  308.  
  309. # If an option that does take an argument is given, an index with its name is
  310. # created in Options and its value is set to the value of the argument given
  311. # for it, and Options[option-name,"count"] is (initially) set to the 1.
  312. # If an option that takes an argument is given more than once,
  313. # Options[option-name,"count"] is incremented, and the value is assigned to
  314. # the index (option-name,instance) where instance is 2 for the second occurance
  315. # of the option, etc.
  316. # In other words, the first time an option with a value is encountered, the
  317. # value is assigned to an index consisting only of its name; for any further
  318. # occurances of the option, the value index has an extra (count) dimension.
  319.  
  320. # The sequence number for each option found in argv[] is stored in
  321. # Options[option-name,"num",instance], where instance is 1 for the first
  322. # occurance of the option, etc.  The sequence number starts at 1 and is
  323. # incremented for each option, both those that have a value and those that
  324. # do not.  Options set from a config file have a value of 0 assigned to this.
  325.  
  326. # Options and their arguments are deleted from argv.
  327. # Note that this means that there may be gaps left in the indices of argv[].
  328. # If compress is nonzero, argv[] is packed by moving its elements so that
  329. # they have contiguous integer indices starting with 0.
  330. # Option processing will stop with the first unrecognized option, just as
  331. # though -- was given except that unlike -- the unrecognized option will not be
  332. # removed from ARGV[].  Normally, an error value is returned in this case.
  333. # If AllowUnrecOpt is true, it is not an error for an unrecognized option to
  334. # be found, so the number of remaining arguments is returned instead.
  335. # If OptChars is not a null string, it is the set of characters that indicate
  336. # that an argument is an option string if the string begins with one of the
  337. # characters.  A string consisting solely of two of the same option-indicator
  338. # characters stops the scanning of argv[].  The default is "-+".
  339. # argv[0] is not examined.
  340. # The number of arguments left in argc is returned.
  341. # If an error occurs, the global string OptErr is set to an error message
  342. # and a negative value is returned.
  343. # Current error values:
  344. # -1: option that required an argument did not get it.
  345. # -2: argument of incorrect type supplied for an option.
  346. # -3: unrecognized (invalid) option.
  347. function ProcArgs(argc,argv,OptList,Options,compress,AllowUnrecOpt,OptChars,
  348. ArgNum,ArgsLeft,Arg,ArgLen,ArgInd,Option,Pos,NumOpt,Value,HadValue,specGiven,
  349. NeedNextOpt,GotValue,OptionNum,Escape,dest,src,count,c,OptTerm,OptCharSet)
  350. {
  351. # ArgNum is the index of the argument being processed.
  352. # ArgsLeft is the number of arguments left in argv.
  353. # Arg is the argument being processed.
  354. # ArgLen is the length of the argument being processed.
  355. # ArgInd is the position of the character in Arg being processed.
  356. # Option is the character in Arg being processed.
  357. # Pos is the position in OptList of the option being processed.
  358. # NumOpt is true if a numeric option may be given.
  359.     ArgsLeft = argc
  360.     NumOpt = index(OptList,"&")
  361.     OptionNum = 0
  362.     if (OptChars == "")
  363.     OptChars = "-+"
  364.     while (OptChars != "") {
  365.     c = substr(OptChars,1,1)
  366.     OptChars = substr(OptChars,2)
  367.     OptCharSet[c]
  368.     OptTerm[c c]
  369.     }
  370.     for (ArgNum = 1; ArgNum < argc; ArgNum++) {
  371.     Arg = argv[ArgNum]
  372.     if (length(Arg) < 2 || !((specGiven = substr(Arg,1,1)) in OptCharSet))
  373.         break    # Not an option; quit
  374.     if (Arg in OptTerm) {
  375.         delete argv[ArgNum]
  376.         ArgsLeft--
  377.         break
  378.     }
  379.     ArgLen = length(Arg)
  380.     for (ArgInd = 2; ArgInd <= ArgLen; ArgInd++) {
  381.         Option = substr(Arg,ArgInd,1)
  382.         if (NumOpt && Option ~ /[-+.0-9]/) {
  383.         # If this option is a numeric option, make its flag be & and
  384.         # its option string flag position be the position of & in
  385.         # the option string.
  386.         Option = "&"
  387.         Pos = NumOpt
  388.         # Prefix Arg with a char so that ArgInd will point to the
  389.         # first char of the numeric option.
  390.         Arg = "&" Arg
  391.         ArgLen++
  392.         }
  393.         # Find position of flag in option string, to get its type (if any).
  394.         # Disallow & as literal flag.
  395.         else if (!(Pos = index(OptList,Option)) || Option == "&") {
  396.         if (AllowUnrecOpt) {
  397.             Escape = 1
  398.             break
  399.         }
  400.         else {
  401.             OptErr = "Invalid option: " specGiven Option
  402.             return -3
  403.         }
  404.         }
  405.  
  406.         # Find what the value of the option will be if it takes one.
  407.         # NeedNextOpt is true if the option specifier is the last char of
  408.         # this arg, which means that if the option requires a value it is
  409.         # the next arg.
  410.         if (NeedNextOpt = (ArgInd >= ArgLen)) { # Value is the next arg
  411.         if (GotValue = ArgNum + 1 < argc)
  412.             Value = argv[ArgNum+1]
  413.         }
  414.         else {    # Value is included with option
  415.         Value = substr(Arg,ArgInd + 1)
  416.         GotValue = 1
  417.         }
  418.  
  419.         if (HadValue = AssignVal(Option,Value,Options,
  420.         substr(OptList,Pos + 1,1),GotValue,"",++OptionNum,!NeedNextOpt,
  421.         specGiven)) {
  422.         if (HadValue < 0)    # error occured
  423.             return HadValue
  424.         if (HadValue == 2)
  425.             ArgInd++    # Account for the single-char value we used.
  426.         else {
  427.             if (NeedNextOpt) {    # option took next arg as value
  428.             delete argv[++ArgNum]
  429.             ArgsLeft--
  430.             }
  431.             break    # This option has been used up
  432.         }
  433.         }
  434.     }
  435.     if (Escape)
  436.         break
  437.     # Do not delete arg until after processing of it, so that if it is not
  438.     # recognized it can be left in ARGV[].
  439.     delete argv[ArgNum]
  440.     ArgsLeft--
  441.     }
  442.     if (compress != 0) {
  443.     dest = 1
  444.     src = argc - ArgsLeft + 1
  445.     for (count = ArgsLeft - 1; count; count--) {
  446.         ARGV[dest] = ARGV[src]
  447.         dest++
  448.         src++
  449.     }
  450.     }
  451.     return ArgsLeft
  452. }
  453.  
  454. # Assignment to values in Options[] occurs only in this function.
  455. # Option: Option specifier character.
  456. # Value: Value to be assigned to option, if it takes a value.
  457. # Options[]: Options array to return values in.
  458. # ArgType: Argument type specifier character.
  459. # GotValue: Whether any value is available to be assigned to this option.
  460. # Name: Name of option being processed.
  461. # OptionNum: Number of this option (starting with 1) if set in argv[],
  462. #     or 0 if it was given in a config file or in the environment.
  463. # SingleOpt: true if the value (if any) that is available for this option was
  464. #     given as part of the same command line arg as the option.  Used only for
  465. #     options from the command line.
  466. # specGiven is the option specifier character use, if any (e.g. - or +),
  467. # for use in error messages.
  468. # Global variables: OptErr
  469. # Return value: negative value on error, 0 if option did not require an
  470. # argument, 1 if it did & used the whole arg, 2 if it required just one char of
  471. # the arg.
  472. # Current error values:
  473. # -1: Option that required an argument did not get it.
  474. # -2: Value of incorrect type supplied for option.
  475. # -3: Bad type given for option &
  476. function AssignVal(Option,Value,Options,ArgType,GotValue,Name,OptionNum,
  477. SingleOpt,specGiven,  UsedValue,Err,NumTypes) {
  478.     # If option takes a value...    [
  479.     NumTypes = "*()#<>]"
  480.     if (Option == "&" && ArgType !~ "[" NumTypes) {    # ]
  481.     OptErr = "Bad type given for & option"
  482.     return -3
  483.     }
  484.  
  485.     if (UsedValue = (ArgType ~ "[:;" NumTypes)) {    # ]
  486.     if (!GotValue) {
  487.         if (Name != "")
  488.         OptErr = "Variable requires a value -- " Name
  489.         else
  490.         OptErr = "option requires an argument -- " Option
  491.         return -1
  492.     }
  493.     if ((Err = CheckType(ArgType,Value,Option,Name,specGiven)) != "") {
  494.         OptErr = Err
  495.         return -2
  496.     }
  497.     # Mark this as a numeric variable; will be propogated to Options[] val.
  498.     if (ArgType != ":" && ArgType != ";")
  499.         Value += 0
  500.     if ((Instance = ++Options[Option,"count"]) > 1)
  501.         Options[Option,Instance] = Value
  502.     else
  503.         Options[Option] = Value
  504.     }
  505.     # If this is an environ or rcfile assignment & it was given a value...
  506.     else if (!OptionNum && Value != "") {
  507.     UsedValue = 1
  508.     # If the value is "0" or "-" and this is the first instance of it,
  509.     # do not set Options[Option]; this allows an assignment in an rcfile to
  510.     # turn off an option (for the simple "Option in Options" test) in such
  511.     # a way that it cannot be turned on in a later file.
  512.     if (!(Option in Options) && (Value == "0" || Value == "-"))
  513.         Instance = 1
  514.     else
  515.         Instance = ++Options[Option]
  516.     # Save the value even though this is a flag
  517.     Options[Option,Instance] = Value
  518.     }
  519.     # If this is a command line flag and has a - following it in the same arg,
  520.     # it is being turned off.
  521.     else if (OptionNum && SingleOpt && substr(Value,1,1) == "-") {
  522.     UsedValue = 2
  523.     if (Option in Options)
  524.         Instance = ++Options[Option]
  525.     else
  526.         Instance = 1
  527.     Options[Option,Instance]
  528.     }
  529.     # If this is a flag assignment without a value, increment the count for the
  530.     # flag unless it was turned off.  The indicator for a flag being turned off
  531.     # is that the flag index has not been set in Options[] but it has an
  532.     # instance count.
  533.     else if (Option in Options || !((Option,1) in Options))
  534.     # Increment number of times this flag seen; will inc null value to 1
  535.     Instance = ++Options[Option]
  536.     Options[Option,"num",Instance] = OptionNum
  537.     return UsedValue
  538. }
  539.  
  540. # Option is the option letter
  541. # Value is the value being assigned
  542. # Name is the var name of the option, if any
  543. # ArgType is one of:
  544. # :    String argument
  545. # ;    Non-null string argument
  546. # *    Floating point argument
  547. # (    Non-negative floating point argument
  548. # )    Positive floating point argument
  549. # #    Integer argument
  550. # <    Non-negative integer argument
  551. # >    Positive integer argument
  552. # specGiven is the option specifier character use, if any (e.g. - or +),
  553. # for use in error messages.
  554. # Returns null on success, err string on error
  555. function CheckType(ArgType,Value,Option,Name,specGiven,  Err,ErrStr) {
  556.     if (ArgType == ":")
  557.     return ""
  558.     if (ArgType == ";") {
  559.     if (Value == "")
  560.         Err = "must be a non-empty string"
  561.     }
  562.     # A number begins with optional + or -, and is followed by a string of
  563.     # digits or a decimal with digits before it, after it, or both
  564.     else if (Value !~ /^[-+]?([0-9]+|[0-9]*\.[0-9]+|[0-9]+\.)$/)
  565.     Err = "must be a number"
  566.     else if (ArgType ~ "[#<>]" && Value ~ /\./)
  567.     Err = "may not include a fraction"
  568.     else if (ArgType ~ "[()<>]" && Value < 0)
  569.     Err = "may not be negative"
  570.     # (
  571.     else if (ArgType ~ "[)>]" && Value == 0)
  572.     Err = "must be a positive number"
  573.     if (Err != "") {
  574.     ErrStr = "Bad value \"" Value "\".  Value assigned to "
  575.     if (Name != "")
  576.         return ErrStr "variable " substr(Name,1,1) " " Err
  577.     else {
  578.         if (Option == "&")
  579.         Option = Value
  580.         return ErrStr "option " specGiven substr(Option,1,1) " " Err
  581.     }
  582.     }
  583.     else
  584.     return ""
  585. }
  586.  
  587. # Note: only the above functions are needed by ProcArgs.
  588. # The rest of these functions call ProcArgs() and also do other
  589. # option-processing stuff.
  590.  
  591. # Opts: Process command line arguments.
  592. # Opts processes command line arguments using ProcArgs()
  593. # and checks for errors.  If an error occurs, a message is printed
  594. # and the program is exited.
  595. #
  596. # Input variables:
  597. # Name is the name of the program, for error messages.
  598. # Usage is a usage message, for error messages.
  599. # OptList the option description string, as used by ProcArgs().
  600. # MinArgs is the minimum number of non-option arguments that this
  601. # program should have, non including ARGV[0] and +h.
  602. # If the program does not require any non-option arguments,
  603. # MinArgs should be omitted or given as 0.
  604. # rcFiles, if given, is a colon-seprated list of filenames to read for
  605. # variable initialization.  If a filename begins with ~/, the ~ is replaced
  606. # by the value of the environment variable HOME.  If a filename begins with
  607. # $, the part from the character after the $ up until (but not including)
  608. # the first character not in [a-zA-Z0-9_] will be searched for in the
  609. # environment; if found its value will be substituted, if not the filename will
  610. # be discarded.
  611. # rcfiles are read in the order given.
  612. # Values given in them will not override values given on the command line,
  613. # and values given in later files will not override those set in earlier
  614. # files, because AssignVal() will store each with a different instance index.
  615. # The first instance of each variable, either on the command line or in an
  616. # rcfile, will be stored with no instance index, and this is the value
  617. # normally used by programs that call this function.
  618. # VarNames is a comma-separated list of variable names to map to options,
  619. # in the same order as the options are given in OptList.
  620. # If EnvSearch is given and nonzero, the first EnvSearch variables will also be
  621. # searched for in the environment.  If set to -1, all values will be searched
  622. # for in the environment.  Values given in the environment will override
  623. # those given in the rcfiles but not those given on the command line.
  624. # NoRCopt, if given, is an additional letter option that if given on the
  625. # command line prevents the rcfiles from being read.
  626. # See ProcArgs() for a description of AllowUnRecOpt and optChars, and
  627. # ExclusiveOptions() for a description of exOpts.
  628. # Special options:
  629. # If x is made an option and is given, some debugging info is output.
  630. # h is assumed to be the help option.
  631.  
  632. # Global variables:
  633. # The command line arguments are taken from ARGV[].
  634. # The arguments that are option specifiers and values are removed from
  635. # ARGV[], leaving only ARGV[0] and the non-option arguments.
  636. # The number of elements in ARGV[] should be in ARGC.
  637. # After processing, ARGC is set to the number of elements left in ARGV[].
  638. # The option values are put in Options[].
  639. # On error, Err is set to a positive integer value so it can be checked for in
  640. # an END block.
  641. # Return value: The number of elements left in ARGV is returned.
  642. # Must keep OptErr global since it may be set by InitOpts().
  643. function Opts(Name,Usage,OptList,MinArgs,rcFiles,VarNames,EnvSearch,NoRCopt,
  644. AllowUnrecOpt,optChars,exOpts,  ArgsLeft,e) {
  645.     if (MinArgs == "")
  646.     MinArgs = 0
  647.     ArgsLeft = ProcArgs(ARGC,ARGV,OptList NoRCopt,Options,1,AllowUnrecOpt,
  648.     optChars)
  649.     if (ArgsLeft < (MinArgs+1) && !("h" in Options)) {
  650.     if (ArgsLeft >= 0) {
  651.         OptErr = "Not enough arguments"
  652.         Err = 4
  653.     }
  654.     else
  655.         Err = -ArgsLeft
  656.     printf "%s: %s.\nUse -h for help.\n%s\n",
  657.     Name,OptErr,Usage > "/dev/stderr"
  658.     exit 1
  659.     }
  660.     if (rcFiles != "" && (NoRCopt == "" || !(NoRCopt in Options)) &&
  661.     (e = InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch)) < 0)
  662.     {
  663.     print Name ": " OptErr ".\nUse -h for help." > "/dev/stderr"
  664.     Err = -e
  665.     exit 1
  666.     }
  667.     if ((exOpts != "") && ((OptErr = ExclusiveOptions(exOpts,Options)) != ""))
  668.     {
  669.     printf "%s: Error: %s\n",Name,OptErr > "/dev/stderr"
  670.     Err = 1
  671.     exit 1
  672.     }
  673.     return ArgsLeft
  674. }
  675.  
  676. # ReadConfFile(): Read a file containing var/value assignments, in the form
  677. # <variable-name><assignment-char><value>.
  678. # Whitespace (spaces and tabs) around a variable (leading whitespace on the
  679. # line and whitespace between the variable name and the assignment character) 
  680. # is stripped.  Lines that do not contain an assignment operator or which
  681. # contain a null variable name are ignored, other than possibly being noted in
  682. # the return value.  If more than one assignment is made to a variable, the
  683. # first assignment is used.
  684. # Input variables:
  685. # File is the file to read.
  686. # Comment is the line-comment character.  If it is found as the first non-
  687. #     whitespace character on a line, the line is ignored.
  688. # Assign is the assignment string.  The first instance of Assign on a line
  689. #     separates the variable name from its value.
  690. # If StripWhite is true, whitespace around the value (whitespace between the
  691. #     assignment char and trailing whitespace on the line) is stripped.
  692. # VarPat is a pattern that variable names must match.  
  693. #     Example: "^[a-zA-Z][a-zA-Z0-9]+$"
  694. # If FlagsOK is true, variables are allowed to be "set" by being put alone on
  695. #     a line; no assignment operator is needed.  These variables are set in
  696. #     the output array with a null value.  Lines containing nothing but
  697. #     whitespace are still ignored.
  698. # Output variables:
  699. # Values[] contains the assignments, with the indexes being the variable names
  700. #     and the values being the assigned values.
  701. # Lines[] contains the line number that each variable occured on.  A flag set
  702. #     is record by giving it an index in Lines[] but not in Values[].
  703. # Return value:
  704. # If any errors occur, a string consisting of descriptions of the errors
  705. # separated by newlines is returned.  In no case will the string start with a
  706. # numeric value.  If no errors occur,  the number of lines read is returned.
  707. function ReadConfigFile(Values,Lines,File,Comment,Assign,StripWhite,VarPat,
  708. FlagsOK,
  709. Line,Status,Errs,AssignLen,LineNum,Var,Val) {
  710.     if (Comment != "")
  711.     Comment = "^" Comment
  712.     AssignLen = length(Assign)
  713.     if (VarPat == "")
  714.     VarPat = "."    # null varname not allowed
  715.     while ((Status = (getline Line < File)) == 1) {
  716.     LineNum++
  717.     sub("^[ \t]+","",Line)
  718.     if (Line == "")        # blank line
  719.         continue
  720.     if (Comment != "" && Line ~ Comment)
  721.         continue
  722.     if (Pos = index(Line,Assign)) {
  723.         Var = substr(Line,1,Pos-1)
  724.         Val = substr(Line,Pos+AssignLen)
  725.         if (StripWhite) {
  726.         sub("^[ \t]+","",Val)
  727.         sub("[ \t]+$","",Val)
  728.         }
  729.     }
  730.     else {
  731.         Var = Line    # If no value, var is entire line
  732.         Val = ""
  733.     }
  734.     if (!FlagsOK && Val == "") {
  735.         Errs = Errs \
  736.         sprintf("\nBad assignment on line %d of file %s: %s",
  737.         LineNum,File,Line)
  738.         continue
  739.     }
  740.     sub("[ \t]+$","",Var)
  741.     if (Var !~ VarPat) {
  742.         Errs = Errs sprintf("\nBad variable name on line %d of file %s: %s",
  743.         LineNum,File,Var)
  744.         continue
  745.     }
  746.     if (!(Var in Lines)) {
  747.         Lines[Var] = LineNum
  748.         if (Pos)
  749.         Values[Var] = Val
  750.     }
  751.     }
  752.     if (Status)
  753.     Errs = Errs "\nCould not read file " File
  754.     close(File)
  755.     return Errs == "" ? LineNum : substr(Errs,2)    # Skip first newline
  756. }
  757.  
  758. # Variables:
  759. # Data is stored in Options[].
  760. # rcFiles, OptList, VarNames, and EnvSearch are as as described for Opts().
  761. # Global vars:
  762. # Sets OptErr.  Uses ENVIRON[].
  763. # If anything is read from any of the rcfiles, sets READ_RCFILE to 1.
  764. function InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch,
  765. Line,Var,Pos,Vars,Map,CharOpt,NumVars,TypesInd,Types,Type,Ret,i,rcFile,
  766. fNames,numrcFiles,filesRead,Err,Values,retStr) {
  767.     split("",filesRead,"")    # make awk know this is an array
  768.     NumVars = split(VarNames,Vars,",")
  769.     TypesInd = Ret = 0
  770.     if (EnvSearch == -1)
  771.     EnvSearch = NumVars
  772.     for (i = 1; i <= NumVars; i++) {
  773.     Var = Vars[i]
  774.     CharOpt = substr(OptList,++TypesInd,1)
  775.     if (CharOpt ~ "^[:;*()#<>&]$")
  776.         CharOpt = substr(OptList,++TypesInd,1)
  777.     Map[Var] = CharOpt
  778.     Types[Var] = Type = substr(OptList,TypesInd+1,1)
  779.     # Do not overwrite entries from environment
  780.     if (i <= EnvSearch && Var in ENVIRON &&
  781.     (Err = AssignVal(CharOpt,ENVIRON[Var],Options,Type,1,Var,0)) < 0)
  782.         return Err
  783.     }
  784.  
  785.     numrcFiles = split(rcFiles,fNames,":")
  786.     for (i = 1; i <= numrcFiles; i++) {
  787.     rcFile = fNames[i]
  788.     if (rcFile ~ "^~/")
  789.         rcFile = ENVIRON["HOME"] substr(rcFile,2)
  790.     else if (rcFile ~ /^\$/) {
  791.         rcFile = substr(rcFile,2)
  792.         match(rcFile,"^[a-zA-Z0-9_]*")
  793.         envvar = substr(rcFile,1,RLENGTH)
  794.         if (envvar in ENVIRON)
  795.         rcFile = ENVIRON[envvar] substr(rcFile,RLENGTH+1)
  796.         else
  797.         continue
  798.     }
  799.     if (rcFile in filesRead)
  800.         continue
  801.     # rcfiles are liable to be given more than once, e.g. UHOME and HOME
  802.     # may be the same
  803.     filesRead[rcFile]
  804.     if ("x" in Options)
  805.         printf "Reading configuration file %s\n",rcFile > "/dev/stderr"
  806.     retStr = ReadConfigFile(Values,Lines,rcFile,"#","=",0,"",1)
  807.     if (retStr > 0)
  808.         READ_RCFILE = 1
  809.     else if (ret != "") {
  810.         OptErr = retStr
  811.         Ret = -1
  812.     }
  813.     for (Var in Lines)
  814.         if (Var in Map) {
  815.         if ((Err = AssignVal(Map[Var],
  816.         Var in Values ? Values[Var] : "",Options,Types[Var],
  817.         Var in Values,Var,0)) < 0)
  818.             return Err
  819.         }
  820.         else {
  821.         OptErr = sprintf(\
  822.         "Unknown var \"%s\" assigned to on line %d\nof file %s",Var,
  823.         Lines[Var],rcFile)
  824.         Ret = -1
  825.         }
  826.     }
  827.  
  828.     if ("x" in Options)
  829.     for (Var in Map)
  830.         if (Map[Var] in Options)
  831.         printf "(%s) %s=%s\n",Map[Var],Var,Options[Map[Var]] > \
  832.         "/dev/stderr"
  833.         else
  834.         printf "(%s) %s not set\n",Map[Var],Var > "/dev/stderr"
  835.     return Ret
  836. }
  837.  
  838. # OptSets is a semicolon-separated list of sets of option sets.
  839. # Within a list of option sets, the option sets are separated by commas.  For
  840. # each set of sets, if any option in one of the sets is in Options[] AND any
  841. # option in one of the other sets is in Options[], an error string is returned.
  842. # If no conflicts are found, nothing is returned.
  843. # Example: if OptSets = "ab,def,g;i,j", an error will be returned due to
  844. # the exclusions presented by the first set of sets (ab,def,g) if:
  845. # (a or b is in Options[]) AND (d, e, or f is in Options[]) OR
  846. # (a or b is in Options[]) AND (g is in Options) OR
  847. # (d, e, or f is in Options[]) AND (g is in Options)
  848. # An error will be returned due to the exclusions presented by the second set
  849. # of sets (i,j) if: (i is in Options[]) AND (j is in Options[]).
  850. # todo: make options given on command line unset options given in config file
  851. # todo: that they conflict with.
  852. function ExclusiveOptions(OptSets,Options,
  853. Sets,SetSet,NumSets,Pos1,Pos2,Len,s1,s2,c1,c2,ErrStr,L1,L2,SetSets,NumSetSets,
  854. SetNum,OSetNum) {
  855.     NumSetSets = split(OptSets,SetSets,";")
  856.     # For each set of sets...
  857.     for (SetSet = 1; SetSet <= NumSetSets; SetSet++) {
  858.     # NumSets is the number of sets in this set of sets.
  859.     NumSets = split(SetSets[SetSet],Sets,",")
  860.     # For each set in a set of sets except the last...
  861.     for (SetNum = 1; SetNum < NumSets; SetNum++) {
  862.         s1 = Sets[SetNum]
  863.         L1 = length(s1)
  864.         for (Pos1 = 1; Pos1 <= L1; Pos1++)
  865.         # If any of the options in this set was given, check whether
  866.         # any of the options in the other sets was given.  Only check
  867.         # later sets since earlier sets will have already been checked
  868.         # against this set.
  869.         if ((c1 = substr(s1,Pos1,1)) in Options)
  870.             for (OSetNum = SetNum+1; OSetNum <= NumSets; OSetNum++) {
  871.             s2 = Sets[OSetNum]
  872.             L2 = length(s2)
  873.             for (Pos2 = 1; Pos2 <= L2; Pos2++)
  874.                 if ((c2 = substr(s2,Pos2,1)) in Options)
  875.                 ErrStr = ErrStr "\n"\
  876.                 sprintf("Cannot give both %s and %s options.",
  877.                 c1,c2)
  878.             }
  879.     }
  880.     }
  881.     if (ErrStr != "")
  882.     return substr(ErrStr,2)
  883.     return ""
  884. }
  885.  
  886. # The value of each instance of option Opt that occurs in Options[] is made an
  887. # index of Set[].
  888. # The return value is the number of instances of Opt in Options.
  889. function Opt2Set(Options,Opt,Set,  count) {
  890.     if (!(Opt in Options))
  891.     return 0
  892.     Set[Options[Opt]]
  893.     count = Options[Opt,"count"]
  894.     for (; count > 1; count--)
  895.     Set[Options[Opt,count]]
  896.     return count
  897. }
  898.  
  899. # The value of each instance of option Opt that occurs in Options[] that
  900. # begins with "!" is made an index of nSet[] (with the ! stripped from it).
  901. # Other values are made indexes of Set[].
  902. # The return value is the number of instances of Opt in Options.
  903. function Opt2Sets(Options,Opt,Set,nSet,  count,aSet,ret) {
  904.     ret = Opt2Set(Options,Opt,aSet)
  905.     for (value in aSet)
  906.     if (substr(value,1,1) == "!")
  907.         nSet[substr(value,2)]
  908.     else
  909.         Set[value]
  910.     return ret
  911. }
  912.  
  913. # Returns true if option Opt was given on the command line.
  914. function CmdLineOpt(Options,Opt,  i) {
  915.     for (i = 1; (Opt,"num",i) in Options; i++)
  916.     if (Options[Opt,"num",i] != 0)
  917.         return 1
  918.     return 0
  919. }
  920. ### End of ProcArgs library
  921.